<?php
/**
 * Created by PhpStorm.
 * User: sunku
 * Date: 2018/2/28
 * Time: 17:58
 */

namespace Admin\Controller;
use Admin\Controller\BaseController;
use Think\Exception;
use Common\ORG\Util\UploadFile;

class DocumentController extends BaseController
{
    /**
     * 构造函数
     * DocumentController constructor.
     */
    public function __construct()
    {
        //无需进行权限检测的功能
        \Org\Auth\AuthUtil::setNoAuthFuncList([
            '/admin/document/docMakeDir',
            '/admin/document/ajaxUploadFile'
        ]);
        parent::__construct();
    }

    public function docList(){
        $name = trim(I('get.name'));
        $page = intval(I('get.page',1));
        $pid = intval(I('get.pid',0));
        $page_size = 15;

        $data = [];
        $data['page'] = $page;
        $data['page_size'] = $page_size;
        $name && $data['name'] = $name;
        $data['pid'] = $pid;

        $result = D('Document','Logic')->searchDocumentList($data);

        //
        if ($pid > 0) {
            $currentData = D('Document','Logic')->getDocumentInfo(['id' => $pid, 'type' => 0], 'pid, file_path');
        } else {
            $currentData = [
                'pid' => 0,
                'file_path' => '/'
            ];
        }
        $page = $result['page'];
        $page_size = $result['page_size'];
        $total = $result['total'];
        $total_page = $result['total_page'];
        $docList = $result['dataList'];

        //生成分页
        $url = "/admin/document/docList?name={$name}&pid={$pid}";
        $page_html = create_page($url, $total, $page, $page_size);
        //数据类型：0 目录 1 文件
        $type = [
            0 => [
                'name' => '目录',
                'class' => 'label-success'
            ],
            1 => [
                'name' => '文件',
                'class' => 'label-warning'
            ]
        ];

        $this->assign('page', $page);
        $this->assign('page_size', $page_size);
        $this->assign('total', $total);
        $this->assign('total_page', $total_page);
        $this->assign('page_html', $page_html);

        $this->assign('name', $name);
        $this->assign('docList', $docList);

        $this->assign('type', $type);
        $this->assign('pid', $pid);
        $this->assign('currentData', $currentData);

        $this->loadFrame('docList');
    }

    /**
     * 编辑文档信息
     */
    public function editDoc(){
        $id = I('get.id');
        $docInfo = [];

        if($id){
            $docInfo = D('Document','Logic')->getDocumentInfo(['id'=>$id]);
        }

        $this->assign('docInfo',$docInfo);
        $this->loadFrame('editDoc');
    }

    /**
     * @return string
     */
    public function ajaxSaveDoc(){
        $id = I('post.id');
        $file_path = I('post.file_path');
        $status = I('post.status');
        $name = I('post.name');

        $data = [];

        $file_path && $data['file_path'] = $file_path;
        $status && $data['status'] = $status;
        $name && $data['name'] = $name;

        if(!$data){
            return Response(201,'提交数据异常');
        }
        if(!$id){
            $result = D('Document','Logic')->addDocument($data);
        }else{
            $data['id'] = $id;
            $result = D('Document','Logic')->updateDocumentInfo($data);
        }
        if(!$result){
            return Response(202,'网络请求异常');
        }
        return Response(999,'请求成功');
    }

    /**
     * @return string
     */
    public function ajaxDeleteDoc(){
        $id = I('post.id');
        if(!$id){
            return Response(201,"参数异常");
        }
        $result = D('Document','Logic')->ajaxDeleteDoc(['id'=>$id]);
        if(!$result){
           return Response(202,'网络请求异常');
        }
        return Response(999,"请求成功");
    }

    /**
     *
     */
    public function docDownloadList(){
        $name = trim(I('get.name'));
        $page = intval(I('get.page',1));
        $page_size = 15;

        $data = [];
        $data['page'] = $page;
        $data['page_size'] = $page_size;
        $name && $data['name'] = $name;

        $result = D('Document','Logic')->searchDocumentList($data);

        $page = $result['page'];
        $page_size = $result['page_size'];
        $total = $result['total'];
        $total_page = $result['total_page'];
        $docList = $result['dataList'];

        //生成分页
        $url = "/admin/document/docDownloadList?name={$name}";
        $page_html = create_page($url, $total, $page, $page_size);

        $this->assign('page', $page);
        $this->assign('page_size', $page_size);
        $this->assign('total', $total);
        $this->assign('total_page', $total_page);
        $this->assign('page_html', $page_html);

        $this->assign('name', $name);
        $this->assign('docList', $docList);

        $this->loadFrame('docDownloadList');
    }

    /**
     * 创建目录
     */
    public function docMakeDir() {

        //上传的目录名
        $name = I('post.name', '', 'htmlspecialchars,trim');
        //上级ID
        $pid = I('post.pid', 0, 'intval');

        $relative_path = rtrim($this->getFilePath($pid), '/') . '/' . $name;   //相对路径
        $absolute_path = C('STATIC_PATH') . $relative_path;  //绝对路径

        //获取路径
        if (!is_dir($absolute_path)) {

            $result = mkdir($absolute_path, 0777, true);

            if ( $result ){
                //目录创建成功
                $data = [
                    'name' => $name,
                    'type' => 0,
                    'pid' => $pid,
                    'level' => substr_count($relative_path, '/'),
                    'file_path' => $relative_path,
                    'status' => 1
                ];
                $result = D('Document','Logic')->addDocument($data);
                if ($result['id'] > 0) {
                    return Response(999,'创建成功');
                }
            } else {
                //目录创建失败
                return Response(201,'目录名称不合法');
            }
        }
        return Response(201,'目录已存在');
    }

    public function ajaxUploadFile() {
        set_time_limit(0);
        ini_set('memory_limit', -1);

        //上级ID
        $pid = I('post.pid', 0, 'intval');

        $relative_path = rtrim($this->getFilePath($pid), '/') . '/';   //相对路径

        if (!empty($_FILES['import']['name'])) {
            $upload = new UploadFile();
            $upload->maxSize = 93145728;
            $upload->saveRule ='';
            $upload->autoCharset = false ;//  禁止字符自动转换
            $upload->allowExts = array('xls','xlsx','doc','pdf','docx','png','jpeg','jpg');
            $upload->savePath = C('STATIC_PATH') . $relative_path;  //绝对路径
            if (!$upload->upload()) {
                return Response(2001,$upload->getErrorMsg());
            }
            //导入数据
            $info = $upload->getUploadFileInfo();

            $file = $relative_path.$info[0]['savename'];

            $data = [
                'name' => $info[0]['savename'],
                'type' => 1,
                'pid' => $pid,
                'level' => substr_count($relative_path, '/'),
                'file_path' => $file,
                'status' => 1
            ];

            $result = D('Document','Logic')->addDocument($data);
            if ($result['id'] > 0) {
                return Response(999,'上传成功',['file'=>$file,'info'=>$info[0]]);
            }
            return Response(2002, '文件上传失败，请重新上传');
        }else{
            return Response(2002,"请选择要上传的文件");
        }
    }

    /**
     * 获取路径
     * @param $pid
     * @return string
     */
    private function getFilePath($pid)
    {
        //默认文件路径
        $file_path = '/attachment/document';
        if ( $pid != 0 ) {
            $currentData = D('Document','Logic')->getDocumentInfo(['id' => $pid, 'type' => 0], 'id,file_path');
            // 没有查到上级目录时，直接返回
            if (empty($currentData)) {
                return Response(201,'无效的目录');
            }
            $file_path = $currentData['file_path'];
        }
        return $file_path;
    }
}